import pymysql  # 导入模块


class MySQL():
    def connect(self):
        '''连接MySQL数据库'''
        try:
            db = pymysql.connect(
                host='localhost',
                port=3306,
                user='root',
                passwd='root',
                db='sra201',
                charset='utf8'
            )
            return db
        except:
            raise Exception("数据库连接失败")

    def implement(self):
        '''执行SQL语句'''
        db = self.connect()
        cursor = db.cursor()
        for i in range(1):
            sql = """select * from test"""
            try:
                cursor.execute(sql)
                # result = cursor.fetchone() # 单条数据
                result = cursor.fetchall()  # 多条数据
                for each in result:
                    db.commit()
                    print('查询结果：', each)
            except:
                db.rollback()
                print("查询失败")

        cursor.close()
        db.close()


if __name__ == '__main__':
    a = MySQL()
    a.implement()
